<?php

namespace Kangcg\Application\Git;

/**
 * git的操作
 * Class Git
 * @property string $token WebHook 密码/签名密钥
 * @property string $path 项目任务地址
 * @property string $sh sh 任务的地址
 * @property bool $is_check 是否验证 token
 * @package Kang\Libs\Git
 */
class Git
{
    const USER_AGENT = 'git-oschina-hook'; //固定为 git-oschina-hook，可用于标识为来自 gitee 的请求
    /**
     * 同步监听
     * @return void
     */
    public function run()
    {
        if ($this->isGitHook() === false || ($this->is_check == true && $this->validateToken() === false)) {
            return;
        }

        $this->pull();
    }

    public function pull()
    {
        if($this->sh){
            $path = $this->path ? $this->path : './';
            $command = "cd {$path} && git pull";
        }else{
            $command = "sh {$this->sh}";
        }

        $output = '';
        exec($command, $output);
        return $output;
    }

    public function event()
    {
        return $_SERVER['HTTP_X_GITEE_EVENT'] ?? '';
    }

    //判断请求是否是GIT发出的请求
    public function isGitHook()
    {
        return isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == self::USER_AGENT;
    }

    //验证密钥
    public function validateToken()
    {
        return isset($_SERVER['HTTP_X_GITEE_TOKEN']) && $this->getSign($_SERVER['HTTP_X-Gitee-Timestamp']);
    }

    /**
     * @param int $timestamp  time() * 1000; //时间的毫秒数
     * @return string
     */
    private function getSign(int $timestamp)
    {
        $stringToSign = $timestamp . "\n" . $this->token;
        $hash = hash_hmac('sha256', $stringToSign, $this->token, true);
        $base64Sign = base64_encode($hash);
        $urlEncodedSign = urlencode($base64Sign);

        return $urlEncodedSign;
    }
}
